<?php

class Application_Model_Coupon extends Application_Model_DomainObject {

    protected $_id;
    protected $_dateCreated; //创建日期
    protected $_no; //优惠券号
    protected $_type; // 类型 1 满减型抵用券 2 通用型抵用券
    protected $_money; //需要达到的金额,0为不限
    protected $_scope; // 使用范围 1 通用 2 国际运单 3 代购
    protected $_discount;  //折扣金额
    protected $_startTime; //开始时间
    protected $_dateExpired; //过期时间
    protected $_status; //状态  1.有效  2.己使用  -1.过期
    protected $_useTime; //使用时间
    protected $_relevance; //关联操作的ID
    protected $_userType; //用户类型
    protected $_password; //密码,如为空则不需要难密码
    protected $_userId; //用户ID
    protected $_name; //优惠券名称
    protected $_batchNo;
    protected $_common; //备注
    protected $_useType; //是否选中

    /**
     * 可用 
     */
    const STATUS_OK = 1;

    /**
     * 已用
     */
    const STATUS_USED = 2;

    /**
     * 已过期
     */
    const STATUS_EXPIRED = -1;
    
    /**
     * 没有使用
     */
    const useType_Default = 0;
    /**
     * 国际运单
     */
    const useType_WayBill = 1;
    /**
     * 代购
     */
    const useType_Order = 2;
    /**
     * 满减型优惠券
     */
    const Type_SatisfyReduce = 1;
    /**
     * 通用型优惠券
     */
    const Type_All = 2;
    /**
     * 首重减免券
     */
    const Type_Abatement = 3;
    /**
     * 通用
     */
    const Scope_All = 1;
    /**
     * 国际运单
     */
    const Scope_Waybill = 2;
    /**
     * 代购
     */
    const Scope_Order = 3;

    /**
     * 验证优惠券是否可用
     * @param type $userId 用户ID
     * @param type $money 用户的订单金额
     * @param type $password 密码,如无需要则不传
     */
    public function isValid($userId, $money, $password) {
        if ($this->_status != Application_Model_Coupon::STATUS_OK)
            return FALSE;

        if ($this->_userId != $userId)
            return FALSE;

        if ($this->_dateExpired < time())
            return FALSE;

        if ($this->_password != NULL && $this->_password != '' && $this->_password == $password)
            return FALSE;

        if ($this->_money > $money)
            return FALSE;

        return TRUE;
    }

    /**
     * 验证优惠券
     * @param type $userId
     * @param type $money
     * @param type $password 
     * @return Application_Model_CouponResult
     */
    public function Validate($userId, $money, $password,$shipId) {
        $validator = $this->getValidator();
        return $validator->Validate($userId, $money, $password,$shipId);
    }

    /**
     * 返回验证器
     * @return type 
     */
    private function getValidator() {
        return Application_Model_Coupons_CouponBase::createCoupon($this);
    }

    /**
     * 根据优惠券号返回一张优惠券
     * @param type $no
     * @return Application_Model_Coupon
     */
    public static function getByNo($no) {
        $db = Application_Model_Coupon::getDao();
        return $db->queryOne(array('no' => $no));
    }
    
    public static function getTypeAll()
    {
        return array(
                   self::Type_SatisfyReduce => "满减型抵用券"
                ,  self::Type_All => "通用型抵用券"
                ,  self::Type_Abatement => "首重减免券"
        );
    }

    public function gettypeName() {
        switch ($this->type) {
            case self::Type_SatisfyReduce:
                return "满减型抵用券";
            case self::Type_All:
                return "通用型抵用券";
            case self::Type_Abatement:
                return "首重减免券";
            default :
                return "通用型抵用券";
        }
    }

    public function getuserTypeName() {
        switch ($this->userType) {
            case 0:
                return "代购";
            default :
                return "代购";
        }
    }
    public static function getbyscope()
    {
        return array(
            self::Scope_All => "所有"
            ,  self::Scope_Waybill => "国际运单"
            ,  self::Scope_Order => "代购订单"
        );
    }
    private static function getDb() {
        return new Application_Model_DbTable_Coupon();
    }

    /*
     * 根据用户名，状态获取当前记录总数
     * @param int $userid 用户序号
     * @param int $state 用户序号
     * @return int
     */

    public static function getItemCount($userid, $state) {
        if($state == -1){
            $where[" status = "] = 1;
            $where[" and userId = "] = $userid;
            $where[" and dateExpired > "] = date("Y-m-d H:i:s");
            $where[" and startTime < "] = date("Y-m-d H:i:s");
            return self::getDao()->count($where);
        }else{
            $bill = new Application_Model_DbTable_Coupon();
            return $bill->getItemCount($userid, $state);
        }
    }

    /**
     * 根据用户ID,返回指定状态的优惠券
     * @param type $userId 用户ID
     * @param type $status 状态
     * @return array 
     */
    public static function getByUser($couponSearch) {
        return Application_Model_Coupon::getDb()->queryAll($couponSearch->getSearchFileds());
    }

    public static function getCountByStatus($couponSearch) {
//        var_dump($couponSearch->getSearchFileds());
        return Application_Model_Coupon::getDb()->count($couponSearch->getSearchFileds());
    }
    
    public static function getByWayId($wayId){
        return self::getDao()->queryAll(array('relevance'=>  $wayId));
    }

    /**
     * 返回优惠券名称 
     */
    public function getTitle() {
        return $this->getValidator()->getTitle();
    }

    public function getDiscountMoney() {
        return $this->_discount;
    }

    /**
     * 查询优惠券
     * @param int $couponSearch 查询条件数组
     * @param int $count  每页显示多少条记录
     * @param int $offset 第几页
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($couponSearch, $count, $offset) {
        $where = $couponSearch->getSearchFileds();
        return Application_Model_Coupon::getDb()->queryPage($where, $couponSearch->getOrder(), $count, $offset);
    }

    /**
     * 根据用户ID和批次号获取用户的优惠券
     * @param type $userId
     * @param type $batchNo 
     */
    public static function search($userId, $batchNo) {
        return Application_Model_Coupon::getDao()->queryAll(array('userId' => $userId, 'batchNo' => $batchNo));
    }

    public static function getByNewFilter($no, $storeno, $startTime, $dateExpired, $batchNo, $status, $pagesize, $pageindex) {
        $where = array();
        $and = '';

        if ($no != NULL) {
            $where[$and . ' no = '] = $no;
            $and = ' and ';
        }

        if ($storeno != NULL) {
            $uwhere[' storeno = '] = $storeno;
            $userItem = Application_Model_User::bystore($storeno);
            if ($userItem) {
                $where[$and . ' userId = '] = $userItem->id;
                $and = ' and ';
            } else {
                return null;
            }
        }

        if ($status != NULL) {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }
        if ($batchNo != NULL) {
            $where[$and . ' batchNo = '] = $batchNo;
            $and = ' and ';
        }
        if ($startTime != NULL) {
            $where[$and . ' startTime >= '] = $startTime;
            $and = ' and ';
        }

        if ($dateExpired != NULL) {
            $where[$and . ' dateExpired <= '] = $dateExpired;
            $and = ' and ';
        }
        return Application_Model_Coupon::getDao()->queryPage($where, 'dateExpired desc ', $pagesize, $pageindex);
    }

    /**
     * 返回用户信息
     */
    public function getuser() {
        return Application_Model_User::load($this->_userId);
    }

    public function getscopeName() {
        switch ($this->_scope) {
            case self::Scope_All:
                return "所有";
            case self::Scope_Waybill:
                return "国际运单";
            case self::Scope_Order:
                return "代购订单";
            default :
                return "所有";
        }
    }
    
    public static function getStatusAll()
    {
        return array(
                    self::STATUS_OK => "未使用"
                ,  self::STATUS_USED => "已使用"
                ,  self::STATUS_EXPIRED => "已过期"
        );
    }


    public function getstatusName() {
        switch ($this->status) {
            case self::STATUS_OK:
                return "未使用";
            case self::STATUS_USED:
                return "已使用";
            case self::STATUS_EXPIRED:
                return "已过期";
            default :
                return "未知状态";
        }
    }
    
    /**
     *  添加优惠券
     * @param type $userId 用户Id
     * @param type $dateExpired 结束时间
     * @param type $password 使用密码
     * @param type $money 底线金额
     * @param type $discount 折扣
     * @param type $comment 备注
     * @param type $type 优惠券类型
     * @param type $scope 使用范围
     * @param type $startTime 开始时间
     * @param type $batchNo 优惠券批次
     * @param type $name 优惠券名称
     */
    public static function addCoupon($userId,$dateExpired,$password,$money,$discount,$comment,$type,$scope,$startTime,$batchNo,$name)
    {
        $couponItem = new Application_Model_Coupon();
        $couponItem->UserId = $userId;
        $couponItem->DateExpired = $dateExpired;
        $couponItem->No = $batchNo.$userId;
        $couponItem->Password = $password;
        $couponItem->Money = $money;
        $couponItem->Discount = $discount;
        $couponItem->DateCreated = date("Y-m-d H:i:s");
        $couponItem->Status = Application_Model_Coupon::STATUS_OK;
        $couponItem->Common = $comment;
        $couponItem->Type = $type;
        $couponItem->scope = $scope;
        $couponItem->StartTime = $startTime;
        $couponItem->UseType = Application_Model_Coupon::useType_Default;
        $couponItem->BatchNo = $batchNo;
        $couponItem->Name = $name;
        $couponItem->save();
        $couponItem->No = $batchNo.$userId.rand(1, 9).$couponItem->Id;
        $couponItem->save();
        return $couponItem;
    }

    public static function getisno($no) {
        $where[' no = '] = $no;
        return Application_Model_Coupon::getDao()->queryOne($where);
    }

//    public static function addcoupon($userId, $no, $arrup) {
//        $couponItem = Application_Model_Coupon::getisno($no);
//        if ($couponItem) {
//            return 22;
//        } else {
//            if ($arrup["batchNo"] != "通用") {
//                $batchItem = Application_Model_Coupon::getcountcoupon($userId, $arrup["batchNo"]);
//                if ($batchItem != 0) {
//                    return 33;
//                }
//            }
//        }
//        $couponObj = new Application_Model_Coupon();
//        foreach ($arrup as $key => $val) {
//            $couponObj->$key = $val;
//        }
//        $couponObj->dateCreated = date("Y-m-d H:i:s");
//        $couponObj->status = self::STATUS_OK;
//        $couponObj->UseType = self::useType_Default;
//        $couponObj->save();
//        $couponBatch = Application_Model_CouponBatch::getByNo($arrup["batchNo"]);
//        $couponBatch->giveCount = $couponBatch->giveCount + 1;
//        $couponBatch->save();
//        return 1;
//    }

    public static function addVouchers($userId,$storeno,$arrup)
    {
        $userItem = Application_Model_User::bystore($storeno);
        if($userItem->Id != $userId){
            return 0;
        }
        $couponItem = new Application_Model_Coupon();
        foreach ($arrup as $key => $value) {
            $couponItem->$key = $value;
        }
        $couponItem->DateCreated = date("Y-m-d H:i:s");
        $couponItem->Money = 0;
        $couponItem->Status = 1;
        $couponItem->Type = 0;
        $couponItem->BatchNo = "NewVouchers";
        $couponItem->No = $couponItem->batchNo.mt_rand(10,99).$userId.mt_rand(0,9);
        $couponItem->Name = $couponItem->discount."元抵用卷";
        $couponItem->UseType = self::useType_Default;
        $couponItem->save();
        Application_Model_Operate::addOperate(0, null, $couponItem->no, "添加".$couponItem->discount."优惠券", $couponItem->userId);
        return 1;
    }

    public static function getcountcoupon($userId, $batchNo) {
        $where[' userId = '] = $userId;
        $where[' and batchNo = '] = $batchNo;
        return Application_Model_Coupon::getDao()->count($where);
    }

    public static function byrelevance($id) {
        $where[" relevance = "] = $id;
        return Application_Model_Coupon::getDao()->queryOne($where);
    }
    
    public static function getcouponByUserIdBatchNo($userId,$batchNo)
    {
        $where[' userId = '] = $userId;
        $where[' and batchNo = '] = $batchNo;
        return Application_Model_Coupon::getDao()->queryAll($where);
    }
    
    public static function getOne($couponSearch)
    {
        return Application_Model_Coupon::getDao()->queryOne($couponSearch->getSearchFileds());
    }
    
    public static function getCount($couponSearch)
    {
        return Application_Model_Coupon::getDao()->count($couponSearch->getSearchFileds());
    }
    
    public function getUserType()
    {
        $storeSearch = new Application_Model_Filter_StoreItemSearch();
        $storeSearch->userId = $this->_userId;
        $count = Application_Model_StoreItem::getCount($storeSearch);
        if($count>1){
            return "老用户";
        }
        return "新用户";
    }
}